<template>
  <el-form v-loading="loading" :model="queryParams" :rules="rules" ref="queryForm" :inline="true">
    <el-form-item label="合同名称" prop="contarctName">
      <el-input
        v-model="queryParams.contarctName"
        placeholder="请输入合同名称"
        clearable
        size="small"
      />
    </el-form-item>
    <el-form-item label="租金合同号" prop="rentCode">
      <el-input
        v-model="queryParams.rentCode"
        placeholder="请输入租金合同号"
        clearable
        size="small"
      />
    </el-form-item>
    <el-form-item label="物管合同号" prop="propertyCode">
      <el-input
        v-model="queryParams.propertyCode"
        placeholder="请输入物管合同号"
        clearable
        size="small"
      />
    </el-form-item>

    <el-divider content-position="left">乙方</el-divider>

    <el-form-item label="客户名称" prop="companyId">
      <el-select v-model="queryParams.companyId" filterable remote
                 @focus="remoteMethods"
                 :remote-method="remoteMethod"
                 :loading="customerloading" placeholder="请输入客户名称" clearable size="small">
        <el-option
          v-for="dict in optionCustomerList"
          :key="dict.id"
          :label="dict.companyName"
          :value="dict.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="联系人" prop="contactName">
      <el-input
        v-model="queryParams.contactName"
        placeholder="联系人"
        clearable
        size="small"
      />
    </el-form-item>
    <el-form-item label="联系电话" prop="contactMobile">
      <el-input
        v-model="queryParams.contactMobile"
        placeholder="联系电话"
        clearable
        size="small"
        maxlength="11"
      />
    </el-form-item>
    <el-form-item label="通讯地址" prop="contactAddress">
      <el-input
        v-model="queryParams.contactAddress"
        placeholder="通讯地址"
        clearable
        size="small"
      />
    </el-form-item>

    <el-divider content-position="left">选择租赁场地</el-divider>

    <el-button class="selectHouse" type="primary" size="mini" @click="selectHouse">选择房间</el-button>

    <el-table
      ref="multipleTable"
      :data="tmpHouseList"
      tooltip-effect="dark"
      style="width: 100%">
      <el-table-column
        label="房间id">
        <template slot-scope="scope">{{ scope.row.houseId }}</template>
      </el-table-column>
      <el-table-column
        label="房间编号">
        <template slot-scope="scope">{{ scope.row.roomNum }}</template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="所属楼宇">
        <template slot-scope="scope">{{ scope.row.buildName }}</template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="所属楼层">
        <template slot-scope="scope">{{ scope.row.floorNum }}</template>
      </el-table-column>
      <el-table-column
        prop="address"
        label="收租面积（平方米）">
        <template slot-scope="scope">{{ scope.row.rentarea }}</template>
      </el-table-column>
    </el-table>

    <div class="el-button-box">
      <el-button icon="el-icon-search" size="mini" @click="cancel">返回</el-button>
      <el-button type="primary" icon="el-icon-refresh" size="mini" @click="next">下一步</el-button>
    </div>

    <!-- 选择房间 -->
    <el-dialog class="selectHouse" title="房间选择" :visible.sync="open" width="700px" append-to-body>

      <el-form :model="houseParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="房间号" prop="builderId">
          <el-input
            v-model="houseParams.roomnumber"
            placeholder="请输入房间号"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="楼宇名称" prop="buildingName">
          <el-input
            v-model="houseParams.buildingName"
            placeholder="请输入房间号"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table v-loading="loading" :data="houseList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="房间id" align="center" prop="houseId"/>
        <el-table-column label="房间编号" align="center" prop="roomNum"/>
        <el-table-column label="所属楼宇" align="center" prop="buildName"/>
        <el-table-column label="所属楼层" align="center" prop="floorNum"/>
        <el-table-column label="出租面积（平方米）" align="center" prop="rentarea"/>
        <!--<el-table-column label="租金类型" align="center" prop="rentUnit"/>
        <el-table-column label="租金（元）" align="center" prop="rentMoney"/>-->
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="housecancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>

    </el-dialog>

  </el-form>
</template>
<style>
  .selectHouse .el-form-item__label {
    width: auto !important;
  }

  .selectHouse .el-form-item__content {
    margin-left: auto !important;
  }
</style>
<script>
  import {listCustomer} from "@/api/customer/customer";
  import {getBFHouse} from "@/api/house/house";
  import {addContarct, getContarctInfo, updateContarct} from "@/api/contarct/contarct";

  export default {
    dicts: ['sys_status', 'contarct_status', 'rent_month_type', 'unit_type'],
    data() {
      return {
        // 选中数组
        ids: [],
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        houseParams: {
          roomnumber: undefined,
          buildingName: undefined
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          contarctName: this.commonRequired("合同名称不能为空！"),
          companyId: this.commonRequired("客户名称不能为空！"),
          contactName: this.commonRequired("联系人不能为空！"),
          contactMobile: [{
            validator: this.conductionData.commonFun.checkPhone,
            trigger: 'blur',
            required: true,
          }]
        },
        tableData: [],
        // 是否显示弹出层
        open: false,
        // 遮罩层
        loading: false,
        houseList: [],
        customerList: [],
        customerSearch: undefined,
        //客户列表
        optionCustomerList: [],
        //客户加载遮罩
        customerloading: false,
        //房间加载遮罩
        houseloading:false,
        tmpHouseList: [],
        sumAllArea: 0,
        sumRentMoney: 0,
        sumPropertyMoney: 0,
        isUpdate: 0 // 0 为新增  1 为编辑
      };
    },
    activated() {
      if (this.$route.query.type != "contarctNew") {
        this.getList();
        this.checkIsUpdate()
      } else {
        this.queryParams = {};
        this.tmpHouseList = [];
      }
      if (this.customerList.length === 0) {
        this.customerSelect();
      }
    },
    created() {
      if (this.$route.query.type != "contarctNew") {
        this.getList();
        this.checkIsUpdate()
      } else {
        this.queryParams = {};
        this.tmpHouseList = [];
      }
      if (this.customerList.length === 0) {
        this.customerSelect();
      }
    },
    methods: {
      commonRequired(value) {
        return this.conductionData.commonFun.commonRequired(value);
      },
      customerSelect() {
        // console.log(1234567)
        this.customerloading = true;
        listCustomer()
          .then(response => {
            // console.log(response)
            this.customerloading = false;
            this.customerList = response.rows;
            this.optionCustomerList = this.customerList;
          })
      },
      /** 查询合同列表 */
      getList() {
        /*this.loading = true;
        listContarct(this.queryParams).then(response => {
          this.contarctList = response.rows;
          this.total = response.total;
          this.loading = false;
        });*/
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          contarctCode: null,
        };
        this.resetForm("form");
      },
      // 搜索
      handleQuery() {
        this.selectBFHouse()
      },
      //重置
      resetQuery() {
        this.reset();
      },
      // 选择房间
      selectHouse() {
        this.open = true;
        this.selectBFHouse()
      },
      // 房间多选框选中数据
      handleSelectionChange(selection) {
        this.sumAllArea = 0
        this.sumRentMoney = 0
        this.sumPropertyMoney = 0
        this.tmpHouseList = selection
        var avg = 0
        for (var i = 0; i < this.tmpHouseList.length; i++) {
          avg++
          this.sumAllArea = this.sumAllArea + this.tmpHouseList[i].rentarea
          this.sumRentMoney = this.sumRentMoney + this.tmpHouseList[i].rentMoney
          this.sumPropertyMoney = this.sumPropertyMoney + this.tmpHouseList[i].propertyMoney
        }
        this.ids = selection.map(item => item.houseId)
        this.single = selection.length !== 1
        this.multiple = !selection.length
        this.conductionData.houseArea = parseFloat((this.sumAllArea).toFixed(2))
        this.conductionData.houseRentPrice = parseFloat((this.sumRentMoney / avg).toFixed(2))
        this.conductionData.houseProperPrice = parseFloat((this.sumPropertyMoney / avg).toFixed(2))
      },
      //房间取消
      housecancel() {
        this.reset();
        this.open = false;
      },
      //房间确定
      submitForm() {
        this.open = false
      },
      /** 下一步 */
      next() {
        this.$refs["queryForm"].validate(valid => {
          if (valid) {
            if (this.tmpHouseList.length === 0) {
              this.$modal.msgError("请选择房间！");
              return
            }
            //新增
            if (this.isUpdate === 0) {
              const request = {
                rentCode: this.queryParams.rentCode,
                propertyCode: this.queryParams.propertyCode,
                contarctName: this.queryParams.contarctName,
                companyId: this.queryParams.companyId,
                contactAddress: this.queryParams.contactAddress,
                contactName: this.queryParams.contactName,
                contactMobile: this.queryParams.contactMobile,
                roomids: this.ids.toString()
              }
              addContarct(request).then(response => {
                this.conductionData.contractId = response.data.id
                console.log("tianjia1", response)
              })
            }
            //编辑
            if (this.isUpdate === 1) {
              const request = {
                id: this.conductionData.updateContractId,
                rentCode: this.queryParams.rentCode,
                propertyCode: this.queryParams.propertyCode,
                contarctName: this.queryParams.contarctName,
                companyId: this.queryParams.companyId,
                contactAddress: this.queryParams.contactAddress,
                contactName: this.queryParams.contactName,
                contactMobile: this.queryParams.contactMobile,
                roomids: this.ids.toString() || this.conductionData.contractInfo.roomids
              }
              var ridArr = request.roomids.split(',')
              //自动加载房屋信息
              this.sumAllArea = 0
              this.sumRentMoney = 0
              this.sumPropertyMoney = 0
              var avg = 0
              for (var i = 0; i < this.tmpHouseList.length; i++) {
                for (var j = 0; j < ridArr.length; j++) {
                  if (this.tmpHouseList[i].houseId === parseInt(ridArr[j])) {
                    avg++
                    this.sumAllArea = this.sumAllArea + this.tmpHouseList[i].rentarea
                    this.sumRentMoney = this.sumRentMoney + this.tmpHouseList[i].rentMoney
                    this.sumPropertyMoney = this.sumPropertyMoney + this.tmpHouseList[i].propertyMoney
                  }
                }
              }
              this.conductionData.houseArea = parseFloat((this.sumAllArea).toFixed(2))
              this.conductionData.houseRentPrice = parseFloat((this.sumRentMoney / avg).toFixed(2))
              this.conductionData.houseProperPrice = parseFloat((this.sumPropertyMoney / avg).toFixed(2))
              updateContarct(request)
                .then(response => {
                  console.log(response)
                })
            }
            this.$emit("ComponentType", "detailsTwo");
          }
        });
      },
      // 返回
      cancel() {
        this.$router.go(-1);
      },
      remoteMethods() {
        this.optionCustomerList = this.customerList;
      },
      // 客户下拉搜索选择
      remoteMethod(query) {
        if (query !== '') {
          this.customerloading = true;
          setTimeout(() => {
            this.customerloading = false;
            this.optionCustomerList = this.customerList.filter(item => {
              return item.companyName.toLowerCase().indexOf(query.toLowerCase()) > -1;
            });
          }, 200);
        } else {
          this.optionCustomerList = this.customerList;
        }
      },
      selectBFHouse() {
        if (this.houseParams.roomnumber === null || this.houseParams.roomnumber === '') {
          this.houseParams.roomnumber = undefined
        }
        if (this.houseParams.buildingName === null || this.houseParams.buildingName === '') {
          this.houseParams.buildingName = undefined
        }
        this.houseloading=true;
        getBFHouse(this.houseParams.roomnumber, this.houseParams.buildingName).then(response => {
          this.houseList = response.data;
          this.houseloading=false;
        })
      },
      checkIsUpdate() {
        this.tmpHouseList = []
        if (this.conductionData.updateContractId !== null && this.conductionData.updateContractId !== undefined && this.conductionData.updateContractId !== 0 && this.conductionData.updateContractId !== '') {
          this.isUpdate = 1//执行修改接口
          //查询待审的合同信息
          this.loading = true;
          getContarctInfo(this.conductionData.updateContractId).then(response => {
            this.queryParams = JSON.parse(JSON.stringify(response.data));
            this.queryParams.companyId = parseFloat(this.queryParams.companyId);
            this.conductionData.contractInfo = response.data
            for (var i = 0; i < response.data.houseInfo.length; i++) {
              const house = {}
              house.houseId = response.data.houseInfo[i].id
              house.roomNum = response.data.houseInfo[i].roomnumber
              house.buildName = response.data.houseInfo[i].houseFloor.houseBuilder.buildingName
              house.floorNum = response.data.houseInfo[i].houseFloor.floorNum
              house.rentarea = response.data.houseInfo[i].rentarea
              house.rentUnit = response.data.houseInfo[i].rentUnit
              house.rentMoney = response.data.houseInfo[i].rentMoney
              house.propertyMoney = response.data.houseInfo[i].propertyMoney
              this.tmpHouseList.push(house)
            }
            this.loading = false;
          })
        }
      }
    }
  };
</script>
